package com.zzt.lotterysystem.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.util.Properties;

@Component
@Slf4j
public class MailUtil {
    private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);

    @Value(value = "${spring.mail.username}")
    private String from;

    @Value(value = "${spring.mail.password}")
    private String password;  // 添加密码/授权码配置

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 配置JavaMailSender以支持SSL/TLS加密
     */
    private JavaMailSender getMailSender() {
        JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();
        javaMailSenderImpl.setHost("smtp.qq.com");  // QQ邮箱SMTP服务器
        javaMailSenderImpl.setPort(465);  // 使用SSL时使用端口465
        javaMailSenderImpl.setUsername(from);  // 发件人邮箱地址
        javaMailSenderImpl.setPassword(password);  // 邮箱授权码

        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");  // 启用SSL
        properties.put("mail.smtp.starttls.enable", "true");  // 启用TLS
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        javaMailSenderImpl.setJavaMailProperties(properties);
        return javaMailSenderImpl;
    }

    /**
     * 发邮件
     *
     * @param to 目标邮件地址
     * @param subject 标题
     * @param context 正文
     * @return
     */
    public Boolean sendSampleMail(String to, String subject, String context) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(context);

        try {
            // 使用配置的JavaMailSender发送邮件
            getMailSender().send(message);
        } catch (Exception e) {
            logger.error("向{}发送邮件失败！", to, e);
            return false;
        }
        return true;
    }
}
